package com.jshan.blog.utils;

import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.UUID;

public class FileUploadUtils {
    /**
     * 生成文件名
     *
     * @param originalFilename 原始文件名
     * @return {@link String}
     */

    public static String generateFileName(String filePath, String originalFilename, String storageType) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String localTime = sdf.format(new Date());
        String pathStr =   localTime + "/";
        if (org.apache.commons.lang3.StringUtils.isNotBlank(storageType) && "local".equals(storageType)) {
            exitPath(filePath + pathStr);
        }
        String extension = StringUtils.getFilenameExtension(originalFilename);
        String fileName = UUID.randomUUID().toString();
        return pathStr + fileName + "." + extension;
    }

    @SneakyThrows
    public static void exitPath(String path) {
        File uploadDir = new File(path);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }
    }
}
